import { createStore } from 'vuex'

// 定义state并给定初始值
const state = {
    loginName: '未登录',
    isLogin: false,
    in: 2, // 已登录用户人数
    
    // 商品数据
    Movies: [
        {
            id: 1,
            name: '野孩子',
            kind: '影视',
            price: 100,
            margin: 10,
            describe: '这是官方商品1',
            img: '../public/hai.jpg'
        }, {
            id: 2,
            name: '刺猬',
            kind: '影视',
            price: 200,
            margin: 10,
            describe: '这是官方商品2',
            img: '../public/ci.jpg'
        }, {
            id: 3,
            name: '断桥',
            kind: '影视',
            price: 300,
            margin: 20,
            describe: '这是官方商品3',
            img: '../public/qiao.jpg'
        }, {
            id: 4,
            name: '大概',
            kind: '音乐',
            price: 700,
            margin: 20,
            describe: '这是官方商品3',
            img: '../public/dagai.jpg'
        }
    ],
    
    // 购物车数据
    mycollection: []
}

// 定义mutations
const mutations = {
    // 登录
    login(state, name) {
        state.isLogin = true;
        state.in++;
        state.loginName = name;
    },
    
    // 登出
    logout(state) {
        state.isLogin = false;
        state.loginName = '未登录';
    },
    
    // 添加商品到购物车
    addToCart(state, product) {
        const existingItem = state.mycollection.find(item => item.id === product.id);
        if (existingItem) {
            existingItem.num += product.num;
        } else {
            state.mycollection.push({
                ...product,
                selected: false
            });
        }
    },
    
    // 更新购物车商品数量
    updateCartQuantity(state, { id, num }) {
        const item = state.mycollection.find(item => item.id === id);
        if (item) {
            item.num = num;
        }
    },
    
    // 切换商品选中状态
    toggleCartItem(state, id) {
        const item = state.mycollection.find(item => item.id === id);
        if (item) {
            item.selected = !item.selected;
        }
    },
    
    // 删除购物车商品
    removeFromCart(state, id) {
        const index = state.mycollection.findIndex(item => item.id === id);
        if (index > -1) {
            state.mycollection.splice(index, 1);
        }
    },
    
    // 清空购物车
    clearCart(state) {
        state.mycollection = [];
    },
    
    // 结算后清空已选商品
    checkout(state) {
        state.mycollection = state.mycollection.filter(item => !item.selected);
    },
    
    // 更新商品库存
    updateProductMargin(state, { id, quantity }) {
        const product = state.Movies.find(item => item.id === id);
        if (product) {
            product.margin -= quantity;
        }
    },
    
    // 添加商品到列表
    addProduct(state, product) {
        // 检查商品是否已存在
        const existingProduct = state.Movies.find(item => item.id === product.id);
        if (!existingProduct) {
            state.Movies.push(product);
        }
    },
    
    // 批量添加商品
    addProducts(state, products) {
        products.forEach(product => {
            const existingProduct = state.Movies.find(item => item.id === product.id);
            if (!existingProduct) {
                state.Movies.push(product);
            }
        });
    }
}

// 定义getters
const getters = {
    // 获取已登录状态
    isLoggedIn: state => state.isLogin,
    
    // 获取用户信息
    userInfo: state => ({
        name: state.loginName,
        isLogin: state.isLogin
    }),
    
    // 获取所有商品
    allProducts: state => state.Movies,
    
    // 获取购物车商品
    cartItems: state => state.mycollection,
    
    // 获取购物车商品总数
    cartItemCount: state => {
        return state.mycollection.reduce((total, item) => total + item.num, 0);
    },
    
    // 获取购物车总价
    cartTotalPrice: state => {
        return state.mycollection
            .filter(item => item.selected)
            .reduce((total, item) => total + (item.price * item.num), 0)
            .toFixed(2);
    },
    
    // 获取购物车选中商品数量
    selectedItemCount: state => {
        return state.mycollection.filter(item => item.selected).length;
    },
    
    // 获取购物车选中商品总数
    selectedItemTotal: state => {
        return state.mycollection
            .filter(item => item.selected)
            .reduce((total, item) => total + item.num, 0);
    }
}

// 定义actions
const actions = {
    // 登录action
    login({ commit }, name) {
        commit('login', name);
    },
    
    // 登出action
    logout({ commit }) {
        commit('logout');
    },
    
    // 添加商品到购物车
    addToCart({ commit, state }, product) {
        // 检查库存
        const originalProduct = state.Movies.find(item => item.id === product.id);
        if (originalProduct && product.num > originalProduct.margin) {
            throw new Error(`库存不足，最多只能选择${originalProduct.margin}件`);
        }
        
        // 更新库存
        commit('updateProductMargin', { id: product.id, quantity: product.num });
        
        // 添加到购物车
        commit('addToCart', product);
    },
    
    // 更新购物车商品数量
    updateCartQuantity({ commit }, { id, num }) {
        if (num < 1) {
            num = 1;
        }
        commit('updateCartQuantity', { id, num });
    },
    
    // 切换商品选中状态
    toggleCartItem({ commit }, id) {
        commit('toggleCartItem', id);
    },
    
    // 删除购物车商品
    removeFromCart({ commit }, id) {
        commit('removeFromCart', id);
    },
    
    // 结算
    checkout({ commit, state }) {
        const selectedItems = state.mycollection.filter(item => item.selected);
        if (selectedItems.length === 0) {
            throw new Error('请选择要购买的商品');
        }
        
        // 计算总价（在清空购物车之前）
        const totalPrice = selectedItems
            .reduce((total, item) => total + (item.price * item.num), 0)
            .toFixed(2);
        
        // 计算总数量
        const totalQuantity = selectedItems.reduce((total, item) => total + item.num, 0);
        
        // 清空已选中的商品
        commit('checkout');
        
        return {
            items: selectedItems,
            totalPrice,
            totalQuantity
        };
    }
}

// 创建store
const store = createStore({
    state,
    mutations,
    getters,
    actions
})

export default store